import logging
import random
import string
import os
from django.conf import settings
from qiniu import Auth, put_file

# 初始化日志器
logger = logging.getLogger('django')


def upload_image2QINIU(image, image_name):
    """
    上传图片到七牛云
    image：Bytes类型的图片
    image_name：图片名
    return：七牛云图片url
    """
    # 防止图片名字重复，在图片名前加上5位随机字符串
    image_name = ''.join(random.sample(string.ascii_letters + string.digits, 5)) + image_name
    # 指定Access_Key和Secret_Key
    access_key = settings.QI_NIU_ACCESS_KEY
    secret_key = settings.QI_NIU_SECRET_KEY
    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 指定要上传的空间
    bucket_name = settings.QI_NIU_BUCKET_NAME
    # 上传后保存的文件名
    key = image_name
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)
    # storage_dir是欲上传文件的所在的本地临时存储文件夹路径
    storage_dir = settings.QINIUYUN_TEMPSTORAGE_DIR
    # image_path是欲上传文件的本地路径
    local_image_path = storage_dir + '/' + image_name

    # 将图片先存储在本地
    with open(local_image_path, 'wb') as f:
        f.write(image)

    # 上传图片到七牛云
    try:
        ret, info = put_file(token, key, local_image_path)
    except Exception as e:
        # 上传出现问题就输出错误信息
        logger.error(e, ret, info)

    # 删除临时文件夹下的文件
    os.remove(local_image_path)

    # 返回云存储图片的URL
    return settings.QI_NIU_BUCKET_HOST + '/' + image_name
